package com.developer.weatherdata.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Color;
import android.os.AsyncTask;
import android.text.Html;
import android.util.Log;
import android.view.View;

import com.developer.weatherdata.activity.MainActivity;
import com.developer.weatherdata.model.Weather;

public class WeatherDownloader extends AsyncTask<String, Void, Weather> {

	public static final String TAG = WeatherDownloader.class.getName();

	private final MainActivity mainActivity;

	public WeatherDownloader(MainActivity mainActivity) {
		this.mainActivity = mainActivity;
	}

	@Override
	protected void onPreExecute() {
		mainActivity.iwRefresh.setVisibility(View.INVISIBLE);
		mainActivity.pbRefreshing.setVisibility(View.VISIBLE);
		mainActivity.rlContainer.setBackgroundColor(Color.parseColor("#FFFC970B"));
	}

	@Override
	protected Weather doInBackground(String... params) {
		String jsonData = downloadJsonData(params[0]);
		return parseJsonData(jsonData);
	}

	@Override
	protected void onPostExecute(Weather result) {
		final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm", new Locale(result.getTimeZone()));
		mainActivity.txtTemperature.setText(String.valueOf(Math.round(result.getTemperature())));
		mainActivity.txtHumidity.setText(String.valueOf(result.getHumidity()));
		mainActivity.txtPrepChance.setText(String.valueOf(result.getPricipitationChance()) + "%");
		mainActivity.txtSummary.setText(result.getSummary());
		mainActivity.txtLocation.setText(result.getTimeZone());
		mainActivity.iwWeatherIcon.setImageDrawable(mainActivity.getResources().getDrawable(result.getIconId()));
		mainActivity.txtTime.setText(String.format("At %s it will be", simpleDateFormat.format(new Date(result.getTime()))));
		mainActivity.iwRefresh.setVisibility(View.VISIBLE);
		mainActivity.pbRefreshing.setVisibility(View.INVISIBLE);
		mainActivity.rlContainer.setBackgroundColor(calculateColor(result.getTemperature()));
	}

	private int calculateColor(double temp) {
		String hexString = Integer.toHexString((int) (temp * 6));
		String result = "#FFFC97" + hexString;
		return Color.parseColor(result);
	}

	private String downloadJsonData(String address) {
		String jsonData = null;
		try {
			URL url = new URL(address);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.connect();
			StringBuilder stringBuilder = new StringBuilder();
			if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
				BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
				String line;
				while ((line = bufferedReader.readLine()) != null) {
					stringBuilder.append(line);
				}
			}
			jsonData = Html.fromHtml(stringBuilder.toString()).toString();
		} catch (Exception e) {
			Log.e(TAG, e.getMessage(), e);
		}
		return jsonData;
	}

	private Weather parseJsonData(String jsonData) {
		Weather weather = new Weather();
		try {
			JSONObject jsonObject = new JSONObject(jsonData);
			JSONObject currentlyJsonObject = jsonObject.getJSONObject("currently");
			weather.setIcon(currentlyJsonObject.getString("icon"));
			weather.setTime(currentlyJsonObject.getLong("time") * 1000);
			weather.setTemperature(currentlyJsonObject.getDouble("temperature"));
			weather.setHumidity(currentlyJsonObject.getDouble("humidity"));
			weather.setPricipitationChance(currentlyJsonObject.getDouble("precipProbability"));
			weather.setSummary(currentlyJsonObject.getString("summary"));
			weather.setTimeZone(jsonObject.getString("timezone"));
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage(), e);
		}
		return weather;
	}

}
